package cn.lili.controller.activity;

import cn.hutool.core.util.ObjectUtil;
import cn.lili.common.enums.ResultCode;
import cn.lili.common.enums.ResultUtil;
import cn.lili.common.security.AuthUser;
import cn.lili.common.security.context.UserContext;
import cn.lili.common.utils.StringUtils;
import cn.lili.common.vo.PageVO;
import cn.lili.common.vo.ResultMessage;
import cn.lili.modules.activity.entity.Activity;
import cn.lili.modules.activity.entity.ActivityGoods;
import cn.lili.modules.activity.entity.vo.ActivityVO;
import cn.lili.modules.activity.service.ActivityGoodsService;
import cn.lili.modules.activity.service.ActivityService;
import cn.lili.modules.goods.entity.vos.GoodsVO;
import cn.lili.modules.goods.service.GoodsService;
import cn.lili.modules.member.entity.dos.Member;
import cn.lili.modules.member.service.MemberService;
import cn.lili.modules.permission.service.AdminUserService;
import cn.lili.modules.permission.service.RoleService;
import cn.lili.modules.store.entity.dos.Store;
import cn.lili.modules.store.service.StoreService;
import cn.lili.modules.system.aspect.annotation.SystemLogPoint;
import cn.lili.modules.system.entity.dos.Region;
import cn.lili.modules.system.service.RegionService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@RestController
@Api(tags = "商家端-活动管理")
@RequestMapping("/store/activity")
public class ActivityStoreController {

	@Autowired
	private ActivityService activityService;

	@Autowired
	private ActivityGoodsService activityGoodsService;

	@Autowired
	private StoreService storeService;

	@Autowired
	private RegionService regionService;

	@Autowired
	private AdminUserService adminUserService;

	@Autowired
	private RoleService roleService;
	@Autowired
	private MemberService memberService;

	/**
	 * 新增或编辑
	 */
	@RequestMapping("/save")
	@SystemLogPoint(description = "新增活动", customerLog = "新增活动请求", type = "2")
	public ResultMessage save(ActivityVO activity) {
		AuthUser authUser = UserContext.getCurrentUser();
		if (ObjectUtil.isNotEmpty(authUser)) {
			if (activityService.getOne(
					new QueryWrapper<Activity>().eq("name", activity.getName()).eq("delete_flag", false)) != null) {
				return ResultUtil.data("保存失败，名字重复");
			}
			activity.setCreateTime(new Date());
			activity.setCreateBy(authUser.getId());
			activity.setPublisher(authUser.getId());
			activity.setStoreId(authUser.getStoreId());
			activity.setSubmitType("2");
			// 查询店铺的adcode
			Store store = storeService.getById(authUser.getStoreId());
			if (ObjectUtil.isEmpty(store)) {
				return ResultUtil.error(ResultCode.STORE_NOT_EXIST);
			}

			String adCode = store.getAdCode();
			if (StringUtils.isNotEmpty(adCode) && !adCode.equals("null")) {
				// 根据店铺的adcode查询是否有城市合伙人
				List<String> list = new ArrayList<>();
				list.add(adCode);
				Region region = regionService.getAdRegionId(adCode);
				String path = region.getPath();
				String[] split = path.split(",");
				for (String s : split) {
					Region region1 = regionService.getById(s);
					if (ObjectUtil.isNotEmpty(region1)) {
						list.add(region1.getAdCode());
					}
				}
				QueryWrapper queryWrapper = new QueryWrapper();
				queryWrapper.in("region_id", list);
				List<String> roleList = roleService.getListRoleId("代理商");
				queryWrapper.in("role_ids", roleList);
				List list1 = adminUserService.list(queryWrapper);
				if (list1.size() > 0) {
					activity.setAuditStatus("0");
				} else {
					activity.setAuditStatus("1");
				}
			} else {
				activity.setAuditStatus("1");
			}
			activity.setDeleteFlag(false);
			activity.setStatus(false);
			if (activity.getRegistrationStartTime() == null) {
				activity.setRegistrationStartTime(new Date(0));
			}
			if (activity.getRegistrationEndTime() == null) {
				activity.setRegistrationEndTime(new Date(0));
			}
			boolean save = activityService.save(activity);
			// 保存商品和活动的关联
			if (save && StringUtils.isNotEmpty(activity.getGoodsList())) {
				String goodsList = activity.getGoodsList();
				String[] split1 = goodsList.split(",");
				for (String s : split1) {
					ActivityGoods activityGoods = new ActivityGoods();
					activityGoods.setGoodsId(s);
					activityGoods.setStoreId(authUser.getStoreId());
					activityGoods.setActivityId(activity.getId());
					activityGoodsService.save(activityGoods);
				}
			}
			return ResultUtil.data("保存成功");
		}
		return ResultUtil.data(ResultCode.TOKEN_OVER);

	}

	/**
	 * 删除
	 */
	@DeleteMapping("/{id}")
	@SystemLogPoint(description = "删除活动", customerLog = "删除活动请求", type = "2")
	public Object delete(@PathVariable String id) {
		Activity activity = activityService.getOne(new QueryWrapper<Activity>().eq("id", id));
		if (activity != null) {
			Activity act = new Activity();
			act.setDeleteFlag(true);
			act.setId(id);
			return ResultUtil.data(activityService.updateById(act));
		} else {
			return ResultUtil.data("没有找到该对象");
		}
	}

	/**
	 * 查询
	 */
	@RequestMapping("/{id}")
	public Object find(@PathVariable String id) {
		ActivityVO activity = activityService.getActivityById(new QueryWrapper<Activity>().eq("a.id", id));
		if (activity != null) {
			return ResultUtil.data(activity);
		} else {
			return ResultUtil.data("没有找到该对象");
		}
	}

	/**
	 * 自动分页查询
	 */
	@RequestMapping("/list")
	public ResultMessage<IPage<ActivityVO>> list(ActivityVO activity, PageVO page) {
		AuthUser authUser = UserContext.getCurrentUser();
		if (ObjectUtil.isNotEmpty(authUser)) {
			activity.setStoreId(authUser.getStoreId());
		}
		activity.setSubmitType("2");
		// auditStatus 0 待审核 1 已审核
		if (StringUtils.isNotEmpty(activity.getAuditStatus()) && activity.getAuditStatus().equals("0")) {
			List<String> stringList = Arrays.asList("0", "1");
			activity.setStatusList(stringList);
		} else if (StringUtils.isNotEmpty(activity.getAuditStatus()) && activity.getAuditStatus().equals("1")) {
			List<String> stringList = Arrays.asList("3", "2", "4");
			activity.setStatusList(stringList);
		}
		return ResultUtil.data(activityService.selectPage(activity, page));
	}

	@PutMapping("/{id}")
	@SystemLogPoint(description = "修改活动", customerLog = "修改活动请求", type = "2")
	public ResultMessage edit(@PathVariable String id, ActivityVO activity) {
		AuthUser authUser = UserContext.getCurrentUser();
		if (ObjectUtil.isNotEmpty(authUser)) {
			activity.setId(id);
			activity.setUpdateBy(authUser.getId());
			activity.setUpdateTime(new Date());
			// 查询店铺的adcode
			Store store = storeService.getById(authUser.getStoreId());
			String adCode = store.getAdCode();
			if (StringUtils.isNotEmpty(adCode) && !adCode.equals("null")) {
				List<String> list = new ArrayList<>();
				list.add(adCode);
				Region region = regionService.getAdRegionId(adCode);
				String path = region.getPath();
				String[] split = path.split(",");
				for (String s : split) {
					Region region1 = regionService.getById(s);
					if (ObjectUtil.isNotEmpty(region1)) {
						list.add(region1.getAdCode());
					}
				}
				QueryWrapper queryWrapper = new QueryWrapper();
				queryWrapper.in("region_id", list);
				List<String> roleList = roleService.getListRoleId("代理商");
				queryWrapper.in("role_ids", roleList);
				List list1 = adminUserService.list(queryWrapper);
				if (list1.size() > 0) {
					activity.setAuditStatus("0");
				} else {
					activity.setAuditStatus("1");
				}
			} else {
				activity.setAuditStatus("1");
			}
			boolean result = activityService.updateById(activity);
			if (result && StringUtils.isNotEmpty(activity.getGoodsList())) {
				QueryWrapper queryWrapper1 = new QueryWrapper();
				queryWrapper1.eq("activity_id", activity.getId());
				activityGoodsService.remove(queryWrapper1);
				String goodsList = activity.getGoodsList();
				String[] split1 = goodsList.split(",");
				for (String s : split1) {
					ActivityGoods activityGoods = new ActivityGoods();
					activityGoods.setGoodsId(s);
					activityGoods.setStoreId(authUser.getStoreId());
					activityGoods.setActivityId(activity.getId());
					activityGoodsService.save(activityGoods);
				}
			}
			return ResultUtil.data(result);
		}
		return ResultUtil.data(ResultCode.TOKEN_OVER);
	}

	/**
	 * 参与活动 - 列表
	 */
	@RequestMapping("/join")
	public ResultMessage<IPage<ActivityVO>> joinActivityList(ActivityVO activityVO, PageVO page) {
		List<String> stringList1 = Arrays.asList("0", "1");
		activityVO.setSubmitType1(stringList1);
		activityVO.setAuditStatus1("3");
		return ResultUtil.data(activityService.joinActivityList(activityVO, page));
	}

	/**
	 * 参与活动 - 选择商品保存
	 */
	@RequestMapping("/save/join")
	@SystemLogPoint(description = "参与活动", customerLog = "参与活动请求", type = "2")
	public ResultMessage saveActivityGoods(ActivityVO activityVO) {
		AuthUser authUser = UserContext.getCurrentUser();
		boolean save = false;
		String goodsList = activityVO.getGoodsList();
		if (StringUtils.isNotEmpty(goodsList)) {
			String[] split1 = goodsList.split(",");
			for (String s : split1) {
				ActivityGoods activityGoods = new ActivityGoods();
				activityGoods.setGoodsId(s);
				activityGoods.setStoreId(authUser.getStoreId());
				activityGoods.setActivityId(activityVO.getActivityId());
				save = activityGoodsService.save(activityGoods);
			}
		}
		return ResultUtil.data("参与成功");
	}

	@PutMapping("/edit/join")
	@SystemLogPoint(description = "修改活动商品", customerLog = "修改活动商品请求", type = "2")
	public ResultMessage editActivityGoods(ActivityVO activityVO) {
		AuthUser authUser = UserContext.getCurrentUser();
		boolean edit = false;
		// 清空活动与之前的商品保存的关联
		QueryWrapper queryWrapper1 = new QueryWrapper();
		queryWrapper1.eq("activity_id", activityVO.getActivityId());
		queryWrapper1.eq("store_id", authUser.getStoreId());
		activityGoodsService.remove(queryWrapper1);
		// 重新保存活动与商品之间的关联
		if (StringUtils.isNotEmpty(activityVO.getGoodsList())) {
			String goodsList = activityVO.getGoodsList();
			String[] split1 = goodsList.split(",");
			for (String s : split1) {
				ActivityGoods activityGoods = new ActivityGoods();
				activityGoods.setGoodsId(s);
				activityGoods.setStoreId(authUser.getStoreId());
				activityGoods.setActivityId(activityVO.getActivityId());
				edit = activityGoodsService.save(activityGoods);
			}
		}
		return ResultUtil.data("修改成功");
	}

}
